import env from "@/lib/seeds/env";
import { sql, Table } from "drizzle-orm";
import * as schema from "@supersavely/db/schema";
import * as seeds from "@/lib/seeds";
import { Pool } from "pg";
import { drizzle } from "drizzle-orm/node-postgres";

console.log(`seed DATABASE_URL: ${env.DATABASE_URL}`);

const pool = new Pool({
  connectionString: env.DATABASE_URL,
});

export const db = drizzle(pool, {
  schema,
  logger: false,
});

export type DB = typeof db;

async function resetTable(db: DB, table: Table) {
  console.log(`Resetting table ${table.name}`);
  return db.execute(sql`truncate table ${table} restart identity cascade`);
}

async function dropAllTables(db: DB) {
  console.warn("DANGER!!! Dropping all tables...");
  db.execute(sql`DROP SCHEMA public CASCADE`);
  db.execute(sql`CREATE SCHEMA public`);
  console.warn("Drop all tables done!");
}

async function initBasicTables() {
  for (const table of [
    // Constants tables, used to initialize the first time
    schema.genders,
    schema.roles,
    schema.mobileCountry,
    schema.users,
    schema.userProfiles,
    schema.userRoles,
    schema.loginLogs,
    // TODO: Add more tables here
    // schema.searchHistory,
    // schema.shoppingCart,
    // schema.shoppingLists,
    // schema.shoppingListItems,
  ]) {
    await resetTable(db, table);
  }
  // await seeds.genders(db);
  // await seeds.roles(db);
  // await seeds.mobileCountry(db);
  await seeds.users(db);
  await seeds.userProfiles(db);
  await seeds.userRoles(db);
}

async function importBranch() {
  console.log("Importing branches...");
  for (const table of [
    schema.branches,
  ]) {
    // await resetTable(db, table);
  }
  await seeds.branches(db);
}


async function importProduct() {
  console.log("Importing products...");
  for (const table of [
    schema.stores,
    schema.categories,
    schema.brands,
    schema.branches,
    schema.products,
    schema.productPriceHistory,
  ]) {
    // await resetTable(db, table);
  }
  await seeds.products(db);
}

async function main() {
  console.log("Starting seeding...");
  // await initBasicTables();
  // await importProduct();
  // await importBranch();
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    console.log("Seeding done!");
    process.exit(0);
  });
